package cn.calm.jbpm4;

import org.hibernate.SessionFactory;
import org.jbpm.api.ProcessEngine;
import org.jbpm.pvm.internal.cfg.ConfigurationImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringHelper implements ApplicationContextAware, DisposableBean {

	  protected ApplicationContext applicationContext;
	  protected String jbpmCfg = "jbpm.cfg.xml";
	  protected ProcessEngine processEngine;
	  @Autowired
	  private SessionFactory sessionFactory;
	  public void setJbpmCfg(String jbpmCfg) {
	    this.jbpmCfg = jbpmCfg;
	  }

	  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	    this.applicationContext = applicationContext;
	  }

	  public ProcessEngine createProcessEngine() {
	    processEngine = new ConfigurationImpl()
	      .springInitiated(applicationContext)
	      .setResource(jbpmCfg)
	      .setHibernateSessionFactory(sessionFactory)
	      .buildProcessEngine();

	    return processEngine;
	  }

	  /**
	   * close process engine when spring close/refresh ctx.
	   */
	  public void destroy() throws Exception {
	    if (processEngine != null) {
	      processEngine.close();
	      processEngine = null;
	    }
	  }

	}
